// script.js
let video, canvas, ctx, mediaInput, loadMediaBtn, clearMediaBtn, opacitySlider, speedSelect;
let captureBtn, beautyFilterBtn, normalFilterBtn, textOverlay, addTextBtn;
let textModal, textInput, confirmTextBtn, cancelTextBtn, textSizeInput;
let textControlPanel, hideTextControlsBtn, filterOptions, optimizationOptions;
let brightnessSlider, smoothnessSlider, filterButtons, photoModeBtn, videoModeBtn;
let photoIcon, videoIcon, recordingIndicator, textScrollSpeed;
let customScrollControls, customScrollDuration, delayBtn;
let videoProgress, currentTimeDisplay, totalTimeDisplay, playPauseBtn;
let isReferenceVideoPlaying = false;
const paused = {current: false}

// 文字滚动速度预设
const scrollSpeedPresets = {
  'very-slow': 180, // 3分钟
  'slow': 120,      // 2分钟
  'normal': 60,     // 1分钟
  'fast': 30,       // 30秒
  'very-fast': 15   // 15秒
};

let mediaElement = null; // 当前加载的参考媒体
let isVideo = false; // 是否为视频
let textContent = ''; // 当前文本内容
let isScrolling = false; // 是否正在滚动
let currentFontSize = 24; // 当前字体大小
let currentMediaUrl = null; // 当前媒体URL

// 拖动相关变量
let isDragging = false;
let currentX;
let currentY;
let initialX;
let initialY;

let scale = 1;
let baseScale = 1;
let lastDistance = 0;

let currentFilter = '';

let isVideoMode = false;
let isRecording = false;
let mediaRecorder = null;
let recordedChunks = [];

// 添加新的状态变量
let autoScrollSpeed = scrollSpeedPresets.normal

let isAutoScrolling = false;
let scrollInterval;
let isPaused = false;
let pauseStartTime = 0;
let scrollStartTime = 0;


// 滤镜预设
const filterPresets = {
  warm: 'brightness(1.1) contrast(1.1) saturate(1.3) sepia(0.3)',
  cool: 'brightness(1.1) contrast(1.1) saturate(0.8) hue-rotate(10deg)',
  vintage: 'brightness(1.1) contrast(1.1) saturate(0.8) sepia(0.4)',
  dramatic: 'brightness(1.2) contrast(1.4) saturate(1.2)',
  sharp: 'brightness(1.1) contrast(1.3) saturate(1.1)'
};

// 添加延时模式变量
let delayMode = 0; // 0: 无延时, 3: 3秒延时, 6: 6秒延时
let countdownTimer = null;

// Add global variables for stream management
let cameraStream = null;
let audioStream = null;

// Constants for scroll speeds (pixels per second)
const SCROLL_SPEEDS = {
  'very-slow': 20,
  'slow': 30,
  'normal': 40,
  'fast': 50,
  'very-fast': 60
};

// 初始化事件监听器
document.addEventListener('DOMContentLoaded', () => {
  try {
    // 添加安全响应头
    const headers = {
      'X-Content-Type-Options': 'nosniff',
      'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
      'Pragma': 'no-cache',
      'Expires': '0'
    };

    // 设置安全响应头
    Object.entries(headers).forEach(([key, value]) => {
      if (document.head) {
        const meta = document.createElement('meta');
        meta.setAttribute('http-equiv', key);
        meta.setAttribute('content', value);
        document.head.appendChild(meta);
      }
    });

    // 初始化DOM元素
    initDOMElements();
    
    // 初始化媒体加载功能
    initMediaControls();
    
    // 初始化文本控件
    initTextControls();
    
    // 初始化拍摄控件
    initCaptureControls();
    
    // 初始化滤镜控件
    initFilterControls();
    
    // 初始化相机和文本覆盖层
    initCamera().then(() => {
    initTextOverlay();
    }).catch(error => {
      console.error('初始化失败:', error);
    });

    // 初始化延时拍摄按钮
    initDelayButton();

    // 初始化播放速度控制
    if (speedSelect) {
      speedSelect.addEventListener('change', () => {
        try {
          const newSpeed = parseFloat(speedSelect.value);
          if (mediaElement && isVideo) {
            mediaElement.playbackRate = newSpeed;
            console.log('视频播放速度已更新:', newSpeed);
          }
        } catch (error) {
          console.error('更新播放速度失败:', error);
          alert('无法更新播放速度，请重试');
        }
      });
    }

    // 初始化文本滚动速度控制
    if (textScrollSpeed) {
      textScrollSpeed.addEventListener('change', previewScrollSpeed);
    }

    // 初始化自定义滚动时间控制
    if (customScrollDuration) {
      customScrollDuration.addEventListener('input', previewScrollSpeed);
    }

    // 初始化触摸事件处理
    initTouchHandling();

  } catch (error) {
    console.error('初始化事件监听器失败:', error);
    alert('初始化失败，请刷新页面重试。错误信息: ' + error.message);
  }
});

// 初始化DOM元素
function initDOMElements() {
  try {
    // 检查必要的DOM元素是否存在
    const requiredElements = [
      'camera-feed',
      'overlay-canvas',
      'media-input',
      'load-media',
      'clear-media',
      'opacity',
      'speed',
      'capture-btn',
      'beauty-filter',
      'normal-filter',
      'text-overlay',
      'add-text',
      'text-modal',
      'text-input',
      'confirm-text',
      'cancel-text',
      'text-size',
      'text-control-panel',
      'hide-text-controls',
      'filter-options',
      'optimization-options',
      'brightness-slider',
      'smoothness-slider',
      'photo-mode',
      'video-mode',
      'text-scroll-speed',
      'custom-scroll-controls',
      'custom-scroll-duration',
      'delay-btn',
      'video-progress',
      'current-time',
      'total-time',
      'play-pause-btn'
    ];

    const missingElements = requiredElements.filter(id => !document.getElementById(id));
    if (missingElements.length > 0) {
      throw new Error(`Missing required elements: ${missingElements.join(', ')}`);
    }

    // 初始化DOM元素
    video = document.getElementById('camera-feed');
    canvas = document.getElementById('overlay-canvas');
    ctx = canvas.getContext('2d');
    mediaInput = document.getElementById('media-input');
    loadMediaBtn = document.getElementById('load-media');
    clearMediaBtn = document.getElementById('clear-media');
    opacitySlider = document.getElementById('opacity');
    speedSelect = document.getElementById('speed');
    captureBtn = document.getElementById('capture-btn');
    beautyFilterBtn = document.getElementById('beauty-filter');
    normalFilterBtn = document.getElementById('normal-filter');
    textOverlay = document.getElementById('text-overlay');
    addTextBtn = document.getElementById('add-text');
    textModal = document.getElementById('text-modal');
    textInput = document.getElementById('text-input');
    confirmTextBtn = document.getElementById('confirm-text');
    cancelTextBtn = document.getElementById('cancel-text');
    textSizeInput = document.getElementById('text-size');
    textControlPanel = document.getElementById('text-control-panel');
    hideTextControlsBtn = document.getElementById('hide-text-controls');
    resetTextPositionBtn = document.getElementById('reset-text-position');
    filterOptions = document.getElementById('filter-options');
    optimizationOptions = document.getElementById('optimization-options');
    brightnessSlider = document.getElementById('brightness-slider');
    smoothnessSlider = document.getElementById('smoothness-slider');
    filterButtons = document.querySelectorAll('.filter-btn');
    photoModeBtn = document.getElementById('photo-mode');
    videoModeBtn = document.getElementById('video-mode');
    photoIcon = document.querySelector('.photo-icon');
    videoIcon = document.querySelector('.video-icon');
    recordingIndicator = document.querySelector('.recording-indicator');
    textScrollSpeed = document.getElementById('text-scroll-speed');
    customScrollControls = document.getElementById('custom-scroll-controls');
    customScrollDuration = document.getElementById('custom-scroll-duration');
    delayBtn = document.getElementById('delay-btn');
    videoProgress = document.getElementById('video-progress');
    currentTimeDisplay = document.getElementById('current-time');
    totalTimeDisplay = document.getElementById('total-time');
    playPauseBtn = document.getElementById('play-pause-btn');

    // 添加必要的标签和标题
    if (mediaInput) {
      mediaInput.setAttribute('title', '选择媒体文件');
      mediaInput.setAttribute('aria-label', '选择媒体文件');
    }
    if (opacitySlider) {
      opacitySlider.setAttribute('title', '调整透明度');
      opacitySlider.setAttribute('aria-label', '调整透明度');
    }
    if (speedSelect) {
      speedSelect.setAttribute('title', '选择播放速度');
      speedSelect.setAttribute('aria-label', '选择播放速度');
      // 为播放速度选项添加标签
      const speedOptions = speedSelect.querySelectorAll('option');
      speedOptions.forEach(option => {
        option.setAttribute('aria-label', option.textContent);
      });
    }
    if (textInput) {
      textInput.setAttribute('title', '输入文本内容');
      textInput.setAttribute('placeholder', '请输入要显示的文本');
    }
    if (textSizeInput) {
      textSizeInput.setAttribute('title', '调整文本大小');
      textSizeInput.setAttribute('aria-label', '调整文本大小');
    }
    if (brightnessSlider) {
      brightnessSlider.setAttribute('title', '调整亮度');
      brightnessSlider.setAttribute('aria-label', '调整亮度');
    }
    if (smoothnessSlider) {
      smoothnessSlider.setAttribute('title', '调整美肤效果');
      smoothnessSlider.setAttribute('aria-label', '调整美肤效果');
    }
    if (customScrollDuration) {
      customScrollDuration.setAttribute('title', '设置自定义滚动时间');
      customScrollDuration.setAttribute('aria-label', '设置自定义滚动时间');
    }
    if (textScrollSpeed) {
      textScrollSpeed.setAttribute('title', '选择文本滚动速度');
      textScrollSpeed.setAttribute('aria-label', '选择文本滚动速度');
      // 为滚动速度选项添加标签
      const scrollSpeedOptions = textScrollSpeed.querySelectorAll('option');
      scrollSpeedOptions.forEach(option => {
        option.setAttribute('aria-label', option.textContent);
      });
    }

    // 检查关键元素是否成功获取
    if (!video || !canvas || !ctx || !textOverlay) {
      throw new Error('Failed to initialize critical elements');
    }

    // Initialize reference controls
    initReferenceControls();

  } catch (error) {
    console.error('初始化DOM元素失败:', error);
    alert('页面初始化失败，请刷新重试。错误信息: ' + error.message);
    throw error; // 重新抛出错误以便上层处理
  }
}

// 初始化媒体加载功能
function initMediaControls() {
  try {
    // 媒体加载按钮
    if (loadMediaBtn) {
      loadMediaBtn.addEventListener('click', () => {
        try {
          if (mediaInput) {
            mediaInput.click();
          }
        } catch (error) {
          console.error('打开媒体选择器失败:', error);
          alert('无法打开媒体选择器，请重试');
        }
      });
    }

    // 媒体文件输入
    if (mediaInput) {
      mediaInput.addEventListener('change', loadMedia);
    }

    // 清除媒体按钮
    if (clearMediaBtn) {
      clearMediaBtn.addEventListener('click', () => {
        try {
          clearMedia();
          // 重置按钮状态
          if (loadMediaBtn) {
            loadMediaBtn.disabled = false;
            loadMediaBtn.textContent = '加载参考';
          }
        } catch (error) {
          console.error('清除媒体失败:', error);
          alert('清除媒体失败，请重试');
        }
      });
    }

    // 透明度滑块
    if (opacitySlider) {
      opacitySlider.addEventListener('input', () => {
        updateOpacity(opacitySlider.value);
      });
    }

    // 播放速度控制
    if (speedSelect) {
      speedSelect.addEventListener('change', () => {
        try {
          const newSpeed = parseFloat(speedSelect.value);
          if (mediaElement && isVideo) {
            mediaElement.playbackRate = newSpeed;
            console.log('视频播放速度已更新:', newSpeed);
          }
        } catch (error) {
          console.error('更新播放速度失败:', error);
          alert('无法更新播放速度，请重试');
        }
      });
    }
  } catch (error) {
    console.error('初始化媒体控件失败:', error);
    alert('初始化媒体控件失败，请刷新页面重试');
  }
}

// 清理媒体资源
function clearMedia() {
  try {
    console.log('开始清理媒体资源');

    // Hide reference controls first
    const referenceControls = document.querySelector('.reference-controls');
    if (referenceControls) {
      referenceControls.style.display = 'none';
    }

    // Clean up media element
    if (mediaElement) {
      // Stop video if it's playing
      if (isVideo && !mediaElement.paused) {
        mediaElement.pause();
      }

      // Remove event listeners
      mediaElement.onloadedmetadata = null;
      mediaElement.ontimeupdate = null;
      mediaElement.onplay = null;
      mediaElement.onpause = null;
      mediaElement.onerror = null;

      // Clear source and remove element
        mediaElement.src = '';
      mediaElement.load(); // Force browser to clear the video buffer

      // Remove from DOM if it's still attached
      if (mediaElement.parentNode) {
        mediaElement.parentNode.removeChild(mediaElement);
      }

      // Clear the reference
      mediaElement = null;
    }

    // Reset video state
    isVideo = false;
    isReferenceVideoPlaying = false;

    // Clear media URL
    if (currentMediaUrl) {
      URL.revokeObjectURL(currentMediaUrl);
      currentMediaUrl = null;
    }

    // Reset file input
    if (mediaInput) {
      mediaInput.value = '';
    }

    // Reset progress bar and time display
    const videoProgress = document.getElementById('video-progress');
    const currentTimeDisplay = document.getElementById('current-time');
    const totalTimeDisplay = document.getElementById('total-time');

    if (videoProgress) {
      videoProgress.value = 0;
    }
    if (currentTimeDisplay) {
      currentTimeDisplay.textContent = '0:00';
    }
    if (totalTimeDisplay) {
      totalTimeDisplay.textContent = '0:00';
    }

    // Reset play/pause button
    const playPauseBtn = document.getElementById('play-pause-btn');
    if (playPauseBtn) {
      const playIcon = playPauseBtn.querySelector('.play-icon');
      const pauseIcon = playPauseBtn.querySelector('.pause-icon');
      if (playIcon) playIcon.style.display = 'block';
      if (pauseIcon) pauseIcon.style.display = 'none';
    }

    // Reset speed select
    const speedSelect = document.getElementById('speed');
    if (speedSelect) {
      speedSelect.value = '1.0';
    }

    console.log('媒体资源清理完成');

  } catch (error) {
    console.error('清理媒体资源失败:', error);
    // Don't show alert, just log the error
    // Continue with cleanup even if there's an error
  }
}

// 加载参考媒体
function loadMedia() {
  try {
    const file = mediaInput.files[0];
    if (!file) {
      throw new Error('未选择文件');
    }

    // Clear existing media first
    clearMedia();

    console.log('开始加载新媒体文件');

    // Create new media URL
    currentMediaUrl = URL.createObjectURL(file);
    
    // Create new media element
    mediaElement = document.createElement(file.type.startsWith('video/') ? 'video' : 'img');
    mediaElement.style.position = 'absolute';
    mediaElement.style.top = '0';
    mediaElement.style.left = '0';
    mediaElement.style.width = '100%';
    mediaElement.style.height = '100%';
    mediaElement.style.objectFit = 'contain';
    mediaElement.style.opacity = opacitySlider.value;
    mediaElement.style.zIndex = '1';
    mediaElement.style.pointerEvents = 'none';
    
    // Set up video-specific properties
    if (file.type.startsWith('video/')) {
      mediaElement.controls = false;
      mediaElement.loop = true;
      mediaElement.muted = true;
      isVideo = true;
      
      // Show reference controls
      const referenceControls = document.querySelector('.reference-controls');
      if (referenceControls) {
        referenceControls.style.display = 'block';
      }

      // Initialize video event listeners
      initVideoEventListeners();
    }

    // Set media source
    mediaElement.src = currentMediaUrl;
    
    // Get camera preview container
    const cameraPreview = document.querySelector('.camera-preview');
    if (!cameraPreview) {
      throw new Error('相机预览容器未找到');
    }
    
    // Find the text overlay element
    const textOverlay = document.getElementById('text-overlay');
    if (!textOverlay) {
      throw new Error('文本覆盖层未找到');
    }

    // Insert media element before text overlay
    cameraPreview.insertBefore(mediaElement, textOverlay);
    
    // Update opacity
    updateOpacity(opacitySlider.value);
    
    console.log('新媒体文件加载完成');

  } catch (error) {
    console.error('加载媒体失败:', error);
    alert('加载媒体失败: ' + error.message);
    clearMedia(); // Clean up if loading fails
  }
}

// Update the initVideoEventListeners function
function initVideoEventListeners() {
  try {
    if (!mediaElement || !isVideo) return;

    // Remove any existing listeners first to prevent duplicates
    mediaElement.removeEventListener('timeupdate', handleTimeUpdate);
    mediaElement.removeEventListener('canplay', handleCanPlay);
    mediaElement.removeEventListener('play', handlePlay);
    mediaElement.removeEventListener('pause', handlePause);

    // Define event handler functions
    function handleTimeUpdate() {
      console.log('视频时间更新事件启动！');
      requestAnimationFrame(() => {
        console.log("视频时间更新", mediaElement, isVideo)
        if (!mediaElement || !isVideo) return;
        const progress = (mediaElement.currentTime / mediaElement.duration) * 100;
        const videoProgress = document.getElementById('video-progress');
        if (videoProgress) {
          videoProgress.value = progress;
        }
        updateTimeDisplay(mediaElement.currentTime, mediaElement.duration);
      });
    }

    function handleCanPlay() {
      console.log('视频可以播放');
      if (mediaElement.duration && !isNaN(mediaElement.duration)) {
        updateTimeDisplay(mediaElement.currentTime, mediaElement.duration);
        updateVideoProgress();
      }
    }

    function handlePlay() {
      console.log('视频开始播放');
      updatePlayPauseButton(true);
      isReferenceVideoPlaying = true;
    }

    function handlePause() {
      console.log('视频已暂停');
      updatePlayPauseButton(false);
      isReferenceVideoPlaying = false;
    }

    // Add event listeners
    mediaElement.addEventListener('timeupdate', handleTimeUpdate);
    mediaElement.addEventListener('canplay', handleCanPlay);
    mediaElement.addEventListener('play', handlePlay);
    mediaElement.addEventListener('pause', handlePause);

    // Progress bar events
    const videoProgress = document.getElementById('video-progress');
    if (videoProgress) {
      videoProgress.addEventListener('input', handleProgressBarInput);
      videoProgress.addEventListener('change', handleProgressBarChange);
    }

    // Speed change event
    const speedSelect = document.getElementById('speed');
    if (speedSelect) {
      speedSelect.addEventListener('change', () => {
        if (mediaElement) {
          mediaElement.playbackRate = parseFloat(speedSelect.value);
        }
      });
    }

        } catch (error) {
    console.error('初始化视频事件监听器失败:', error);
  }
}

// Update the updateVideoProgress function to use requestAnimationFrame
function updateVideoProgress() {
  try {
    requestAnimationFrame(() => {
      const videoProgress = document.getElementById('video-progress');
      if (!mediaElement || !isVideo || !videoProgress) return;

      if (mediaElement.duration && !isNaN(mediaElement.duration)) {
        const progress = (mediaElement.currentTime / mediaElement.duration) * 100;
        videoProgress.value = progress;
      }
    });
        } catch (error) {
    console.error('更新视频进度失败:', error);
  }
}

// Update the updateTimeDisplay function
function updateTimeDisplay(currentTime, duration) {
  try {
    const currentTimeDisplay = document.getElementById('current-time');
    const totalTimeDisplay = document.getElementById('total-time');
    
    if (!currentTimeDisplay || !totalTimeDisplay) return;

    // Ensure we have valid numbers
    currentTime = isNaN(currentTime) ? 0 : currentTime;
    duration = isNaN(duration) ? 0 : duration;

    console.log('更新时间显示:', currentTime, duration);
    currentTimeDisplay.textContent = formatTime(currentTime);
    totalTimeDisplay.textContent = formatTime(duration);
        } catch (error) {
    console.error('更新时间显示失败:', error);
  }
}

// Update the handleProgressBarInput function
function handleProgressBarInput(e) {
  try {
    if (!mediaElement || !isVideo) return;
    
    const time = (mediaElement.duration * e.target.value) / 100;
    console.log('进度条输入:', time);
    updateTimeDisplay(time, mediaElement.duration);
        } catch (error) {
    console.error('进度条输入处理失败:', error);
  }
}

// Update the handleProgressBarChange function
function handleProgressBarChange(e) {
  try {
    if (!mediaElement || !isVideo) return;
    
    const time = (mediaElement.duration * e.target.value) / 100;
    console.log('进度条改变:', time);
    mediaElement.currentTime = time;
    updateTimeDisplay(time, mediaElement.duration);
        } catch (error) {
    console.error('进度条更改处理失败:', error);
  }
}

// 初始化文本控件
function initTextControls() {
  try {
    const addTextBtn = document.getElementById('add-text');
    const textModal = document.getElementById('text-modal');
    const textInput = document.getElementById('text-input');
    const confirmTextBtn = document.getElementById('confirm-text');
    const cancelTextBtn = document.getElementById('cancel-text');
    const textControlPanel = document.getElementById('text-control-panel');

    if (!addTextBtn || !textModal || !textInput || !confirmTextBtn || !cancelTextBtn) {
      throw new Error('Basic text control elements not found');
    }

    // Add text button click handler
    addTextBtn.addEventListener('click', () => {
      textModal.style.display = 'flex';
      textInput.value = '';
      textInput.focus();
    });

    // Confirm text button click handler
    confirmTextBtn.addEventListener('click', () => {
      const text = textInput.value.trim();
      if (text) {
        console.log('Confirming text:', text);
        textModal.style.display = 'none';
        showTextOverlay(text);
        if (textControlPanel) {
          textControlPanel.style.display = 'block';
        }
      }
    });

    // Cancel text button click handler
    cancelTextBtn.addEventListener('click', () => {
      textModal.style.display = 'none';
    });

    console.log('Text controls initialized successfully');

  } catch (error) {
    console.error('初始化文本控件失败:', error);
    alert('初始化文本控件失败: ' + error.message);
  }
}

// 初始化滤镜控件
function initFilterControls() {
  try {
    // 美颜按钮
    if (beautyFilterBtn) {
      beautyFilterBtn.addEventListener('click', () => {
        try {
          // 如果正在录制，不响应点击
          if (isRecording) {
            alert('录制过程中无法更改滤镜');
            return;
          }
          
          const wasActive = beautyFilterBtn.classList.contains('active');
          
          beautyFilterBtn.classList.toggle('active');
          if (normalFilterBtn) {
            normalFilterBtn.classList.remove('active');
          }
          
          if (wasActive) {
            if (filterOptions) filterOptions.style.display = 'none';
            if (optimizationOptions) optimizationOptions.style.display = 'none';
            resetFilters();
          } else {
            if (filterOptions) filterOptions.style.display = 'block';
            if (optimizationOptions) optimizationOptions.style.display = 'block';
            applyFilters();
          }
        } catch (error) {
          console.error('切换美颜模式失败:', error);
          alert('无法切换美颜模式，请重试');
          // 重置滤镜状态
          beautyFilterBtn.classList.remove('active');
          if (normalFilterBtn) normalFilterBtn.classList.add('active');
          if (filterOptions) filterOptions.style.display = 'none';
          if (optimizationOptions) optimizationOptions.style.display = 'none';
          resetFilters();
        }
      });
    }

    // 普通模式按钮
    if (normalFilterBtn) {
      normalFilterBtn.addEventListener('click', () => {
        try {
          // 如果正在录制，不响应点击
          if (isRecording) {
            alert('录制过程中无法更改滤镜');
            return;
          }
          
          normalFilterBtn.classList.add('active');
          if (beautyFilterBtn) beautyFilterBtn.classList.remove('active');
          if (filterOptions) filterOptions.style.display = 'none';
          if (optimizationOptions) optimizationOptions.style.display = 'none';
          currentFilter = '';
          resetFilters();
          if (video) {
            video.style.filter = 'none';
          }
        } catch (error) {
          console.error('切换普通模式失败:', error);
          alert('无法切换普通模式，请重试');
          // 重置滤镜状态
          if (beautyFilterBtn) beautyFilterBtn.classList.add('active');
          normalFilterBtn.classList.remove('active');
          if (filterOptions) filterOptions.style.display = 'block';
          if (optimizationOptions) optimizationOptions.style.display = 'block';
          applyFilters();
        }
      });
    }

    // 滤镜按钮
    if (filterButtons) {
      filterButtons.forEach(btn => {
        btn.addEventListener('click', () => {
          try {
            // 如果正在录制，不响应点击
            if (isRecording) {
              alert('录制过程中无法更改滤镜');
              return;
            }
            
            // 移除其他按钮的active状态
            filterButtons.forEach(b => b.classList.remove('active'));
            // 添加当前按钮的active状态
            btn.classList.add('active');
            // 设置当前滤镜
            currentFilter = btn.dataset.filter;
            // 应用滤镜
            applyFilters();
          } catch (error) {
            console.error('应用滤镜失败:', error);
            alert('无法应用滤镜效果，请重试');
            // 重置滤镜状态
            currentFilter = '';
            filterButtons.forEach(b => b.classList.remove('active'));
            resetFilters();
          }
        });
      });
    }

    // 亮度滑块
    if (brightnessSlider) {
      brightnessSlider.addEventListener('input', () => {
        try {
          applyFilters();
        } catch (error) {
          console.error('更新亮度失败:', error);
          alert('无法更新亮度，请重试');
        }
      });
    }

    // 美肤滑块
    if (smoothnessSlider) {
      smoothnessSlider.addEventListener('input', () => {
        try {
          applyFilters();
        } catch (error) {
          console.error('更新美肤效果失败:', error);
          alert('无法更新美肤效果，请重试');
        }
      });
    }

    // 关闭按钮
    const closeFilterOptionsBtn = document.getElementById('close-filter-options');
    const closeOptimizationOptionsBtn = document.getElementById('close-optimization-options');

    if (closeFilterOptionsBtn) {
      closeFilterOptionsBtn.addEventListener('click', () => {
        try {
          if (filterOptions) {
            filterOptions.style.display = 'none';
          }
        } catch (error) {
          console.error('关闭滤镜选项失败:', error);
          alert('无法关闭滤镜选项，请重试');
        }
      });
    }

    if (closeOptimizationOptionsBtn) {
      closeOptimizationOptionsBtn.addEventListener('click', () => {
        try {
          if (optimizationOptions) {
            optimizationOptions.style.display = 'none';
          }
        } catch (error) {
          console.error('关闭优化选项失败:', error);
          alert('无法关闭优化选项，请重试');
        }
      });
    }
  } catch (error) {
    console.error('初始化滤镜控件失败:', error);
    alert('初始化滤镜控件失败，请刷新页面重试');
  }
}

// 初始化拍摄控件
function initCaptureControls() {
  try {
    // 拍照/录像模式切换
    if (photoModeBtn && videoModeBtn) {
      // 设置初始状态
      photoModeBtn.classList.add('active');
      videoModeBtn.classList.remove('active');
      photoIcon.style.display = 'block';
      videoIcon.style.display = 'none';
      captureBtn.title = '拍照';
      captureBtn.disabled = false;

      photoModeBtn.addEventListener('click', () => {
        try {
          if (isRecording) {
            alert('录制过程中无法切换模式');
            return;
          }
          isVideoMode = false;
          photoModeBtn.classList.add('active');
          videoModeBtn.classList.remove('active');
          photoIcon.style.display = 'block';
          videoIcon.style.display = 'none';
          captureBtn.title = '拍照';
          captureBtn.disabled = false;
          console.log('切换到拍照模式');
        } catch (error) {
          console.error('切换拍照模式失败:', error);
          alert('无法切换拍照模式，请重试');
        }
      });

      videoModeBtn.addEventListener('click', () => {
        try {
          if (isRecording) {
            alert('录制过程中无法切换模式');
            return;
          }
          isVideoMode = true;
          videoModeBtn.classList.add('active');
          photoModeBtn.classList.remove('active');
          videoIcon.style.display = 'block';
          photoIcon.style.display = 'none';
          captureBtn.title = '录像';
          captureBtn.disabled = false;
          console.log('切换到录像模式');
        } catch (error) {
          console.error('切换录像模式失败:', error);
          alert('无法切换录像模式，请重试');
        }
      });
    }

    // 拍摄按钮
    if (captureBtn) {
      captureBtn.addEventListener('click', () => {
        try {
          console.log('拍摄按钮被点击');
          console.log('当前模式:', isVideoMode ? '录像' : '拍照');
          console.log('是否正在录制:', isRecording);

          if (isRecording) {
            console.log('停止录制');
            stopRecording();
          } else {
            console.log('开始拍摄');
            startCapture();
          }
        } catch (error) {
          console.error('拍摄操作失败:', error);
          alert('拍摄失败，请重试');
          resetRecordingState();
        }
      });
    }

    // 初始化录制状态
    resetRecordingState();

    // 检查浏览器是否支持 MediaRecorder
    if (!window.MediaRecorder) {
      console.warn('您的浏览器不支持视频录制功能');
      return;
    }

    // 检查支持的MIME类型
    const mimeTypes = [
      'video/webm;codecs=vp8,opus',
      'video/webm;codecs=vp9',
      'video/webm',
      'video/mp4'
    ];

    const supportedMimeType = mimeTypes.find(type => MediaRecorder.isTypeSupported(type));
    if (!supportedMimeType) {
      console.warn('未找到支持的视频编码格式');
    }

  } catch (error) {
    console.error('初始化拍摄控件失败:', error);
    alert('初始化拍摄控件失败，请刷新页面重试');
  }
}

// 更新透明度
function updateOpacity(value) {
  try {
    if (mediaElement) {
      mediaElement.style.opacity = value;
    }
  } catch (error) {
    console.error('更新透明度失败:', error);
    alert('无法更新透明度，请重试');
  }
}

// 预览滚动速度
function previewScrollSpeed() {
  try {
    const value = textScrollSpeed.value;
    if (value === 'custom') {
      if (customScrollControls) {
        customScrollControls.style.display = 'flex';
      }
      const duration = parseInt(customScrollDuration.value);
      if (duration >= 10 && duration <= 300) {
        autoScrollSpeed = duration;
      }
    } else {
      if (customScrollControls) {
        customScrollControls.style.display = 'none';
      }
      autoScrollSpeed = scrollSpeedPresets[value] || 1;
    }
    
    if (isAutoScrolling && !isPaused) {
      stopAutoScroll();
      startAutoScroll();
    }
  } catch (error) {
    console.error('预览滚动速度失败:', error);
    alert('无法预览滚动速度，请重试');
  }
}

// 开始倒计时
function startCountdown() {
  try {
    if (countdownTimer) {
      clearInterval(countdownTimer);
    }
    
    const countdownOverlay = document.getElementById('countdown-overlay');
    const countdownNumber = countdownOverlay.querySelector('.countdown-number');
    
    if (!countdownOverlay || !countdownNumber) {
      throw new Error('倒计时元素未找到');
    }
    
    // Show countdown overlay and add active class
    countdownOverlay.style.display = 'flex';
    countdownOverlay.classList.add('active');
    
    let count = delayMode;
    countdownNumber.textContent = count;
    
    // Start countdown
    countdownTimer = setInterval(() => {
      count--;
      countdownNumber.textContent = count;
      
      if (count <= 0) {
        clearInterval(countdownTimer);
        countdownTimer = null;
        countdownOverlay.style.display = 'none';
        countdownOverlay.classList.remove('active');
        
        // Synchronize with video material if present
        if (mediaElement && isVideo) {
          mediaElement.currentTime = 0; // Reset video to start
          mediaElement.play().then(() => {
            // Start actual capture after ensuring video is playing
            if (isVideoMode) {
              startRecording();
            } else {
              capturePhoto();
            }
          }).catch(error => {
            console.error('视频同步播放失败:', error);
            alert('无法同步视频材料，请重试');
          });
        } else {
          // No video material, start capture directly
          if (isVideoMode) {
            startRecording();
          } else {
            capturePhoto();
          }
        }
      }
    }, 1000);
  } catch (error) {
    console.error('开始倒计时失败:', error);
    alert('无法开始倒计时，请重试');
    if (countdownTimer) {
      clearInterval(countdownTimer);
      countdownTimer = null;
    }
  }
}

// 修改显示文本覆盖层函数，移除背景色
function showTextOverlay(text) {
  try {
    console.log('Showing text overlay with text:', text);
    
    // Get text overlay elements
    const textOverlay = document.getElementById('text-overlay');
    if (!textOverlay) {
      throw new Error('Text overlay container not found');
    }

    // Ensure text content container exists or create it
    let textContent = textOverlay.querySelector('.text-content');
    if (!textContent) {
      textContent = document.createElement('div');
      textContent.className = 'text-content';
      textOverlay.appendChild(textContent);
    }

    // Set text content
    textContent.textContent = text;
    
    // Ensure control buttons exist
    let playPauseBtn = textOverlay.querySelector('.play-pause-btn');
    if (!playPauseBtn) {
      playPauseBtn = document.createElement('button');
      playPauseBtn.className = 'play-pause-btn';
      playPauseBtn.innerHTML = `
        <span class="play-icon">▶</span>
        <span class="pause-icon" style="display: none;">⏸</span>
      `;
      textOverlay.appendChild(playPauseBtn);
    }

    let closeBtn = textOverlay.querySelector('.close-btn');
    if (!closeBtn) {
      closeBtn = document.createElement('button');
      closeBtn.className = 'close-btn';
      closeBtn.innerHTML = '×';
      textOverlay.appendChild(closeBtn);
    }

    // Show the overlay
    textOverlay.style.display = 'block';
    textOverlay.classList.add('active');

    // Position the overlay
    textOverlay.style.left = '50%';
    textOverlay.style.top = '50%';
    textOverlay.style.transform = 'translate(-50%, -50%)';

    // Initialize scroll controls
    setTimeout(() => {
      initTextScrollControl();
    }, 100);

    console.log('Text overlay shown successfully');

  } catch (error) {
    console.error('显示文本失败:', error);
    alert('显示文本失败: ' + error.message);
  }
}

// Add CSS to ensure text overlay is visible
const style = document.createElement('style');
style.textContent = `
  #text-overlay {
    position: absolute;
    max-height: 70vh;
    width: 80%;
    max-width: 500px;
    background: transparent;
    border-radius: 12px;
    color: white;
    font-size: 18px;
    line-height: 1.6;
    z-index: 1000;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  }

  #text-overlay.active {
    display: block;
  }

  .text-content {
    padding: 40px 20px;
    height: 100%;
    overflow-y: auto;
    white-space: pre-wrap;
    word-break: break-word;
    scrollbar-width: thin;
    scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
  }

  .play-pause-btn, .close-btn {
    background: rgba(0, 0, 0, 0.5) !important;
    backdrop-filter: blur(5px);
  }

  .play-pause-btn:hover, .close-btn:hover {
    background: rgba(0, 0, 0, 0.7) !important;
  }
`;
document.head.appendChild(style);

// 应用滤镜和优化效果
function applyFilters() {
  try {
    let filterString = '';
    
    // Apply base filter
    if (currentFilter && filterPresets[currentFilter]) {
      filterString = filterPresets[currentFilter];
    }
    
    // Apply brightness and smoothness
    if (brightnessSlider && smoothnessSlider) {
      const brightness = parseFloat(brightnessSlider.value);
      const smoothness = parseFloat(smoothnessSlider.value);
      
      if (brightness !== 1) {
        filterString += (filterString ? ' ' : '') + `brightness(${brightness})`;
      }
      
      if (smoothness > 0) {
        filterString += (filterString ? ' ' : '') + `blur(${smoothness * 0.5}px)`;
      }
    }
    
    // Apply beauty effect
    if (beautyFilterBtn && beautyFilterBtn.classList.contains('active')) {
      filterString += (filterString ? ' ' : '') + 'brightness(1.1) contrast(1.1) saturate(1.2)';
    }
    
    // Apply filter using style property instead of CSS rules
    if (video) {
      video.style.filter = filterString || 'none';
    }
  } catch (error) {
    console.error('应用滤镜失败:', error);
    alert('无法应用滤镜效果，请重试');
  }
}

// 重置滤镜
function resetFilters() {
  try {
    if (brightnessSlider) {
      brightnessSlider.value = 1.2;
    }
    if (smoothnessSlider) {
      smoothnessSlider.value = 0;
    }
    if (video) {
      video.style.filter = 'none';
    }
    currentFilter = '';
    if (filterButtons) {
      filterButtons.forEach(btn => btn.classList.remove('active'));
    }
    if (beautyFilterBtn) {
      beautyFilterBtn.classList.remove('active');
    }
  } catch (error) {
    console.error('重置滤镜失败:', error);
    alert('无法重置滤镜效果，请重试');
  }
}

// 初始化相机和文本覆盖层
function initCamera() {
  return new Promise((resolve, reject) => {
  try {
      console.log('开始初始化相机和麦克风');
    
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        reject(new Error('您的浏览器不支持摄像头或麦克风访问'));
      return;
    }

      // Request both camera and microphone permissions at once
    navigator.mediaDevices.getUserMedia({ 
      video: {
        width: { ideal: 1920 },
        height: { ideal: 1080 },
        facingMode: 'user'
        },
        audio: true
    })
    .then(stream => {
        console.log('成功获取摄像头和麦克风权限');
        
        // Separate video and audio streams
        const videoTracks = stream.getVideoTracks();
        const audioTracks = stream.getAudioTracks();

        // Create separate streams
        cameraStream = new MediaStream(videoTracks);
        audioStream = new MediaStream(audioTracks);

        // Set up video preview
      if (video) {
          video.srcObject = cameraStream;
        video.play().then(() => {
            console.log('视频预览开始播放');
            video.style.display = 'block';
            resolve(stream);
        }).catch(error => {
            console.error('视频预览播放失败:', error);
            video.style.display = 'none';
            reject(error);
        });
      }
    })
    .catch(error => {
        console.error('获取设备权限失败:', error);
        let errorMessage = '无法访问摄像头或麦克风，请确保已授予权限';
        if (error.name === 'NotAllowedError') {
          errorMessage = '请允许访问摄像头和麦克风以继续使用';
        } else if (error.name === 'NotFoundError') {
          errorMessage = '未找到摄像头或麦克风设备';
        }
        alert(errorMessage);
        reject(error);
    });
  } catch (error) {
      console.error('初始化设备失败:', error);
      reject(error);
    }
  });
}

// 初始化文本位置和大小
function initTextOverlay() {
  try {
    if (!textOverlay) return;
    
    const textContainer = textOverlay.querySelector('.text-content');
    if (!textContainer) return;
    
    // 重置滚动位置
    textContainer.scrollTop = 0;
    
    // 设置文本容器样式
    textContainer.style.position = 'relative';
    textContainer.style.width = '100%';
    textContainer.style.height = '100%';
    textContainer.style.overflow = 'hidden';
    textContainer.style.whiteSpace = 'pre-wrap';
    textContainer.style.wordBreak = 'break-word';
    textContainer.style.padding = '20px';
    textContainer.style.boxSizing = 'border-box';
    
    // 设置初始位置和大小
    textOverlay.style.left = '50%';
    textOverlay.style.top = '50%';
    textOverlay.style.transform = 'translate(-50%, -50%)';
    textOverlay.style.minWidth = '200px';
    textOverlay.style.minHeight = '100px';
    textOverlay.style.maxWidth = '80%';
    textOverlay.style.maxHeight = '80%';
    scale = 1;
    
    // 初始化拖动和缩放事件
    initDragAndScale();
  } catch (error) {
    console.error('初始化文本覆盖层失败:', error);
    alert('初始化文本覆盖层失败，请刷新页面重试');
  }
}

// 初始化拖动和缩放功能
function initDragAndScale() {
  try {
    if (!textOverlay) return;

    // 添加触摸事件监听器
    textOverlay.addEventListener('touchstart', handleTouchStart, { passive: false });
    textOverlay.addEventListener('touchmove', handleTouchMove, { passive: false });
    textOverlay.addEventListener('touchend', handleTouchEnd);

    // 添加鼠标事件监听器
    textOverlay.addEventListener('mousedown', handleMouseDown);
    textOverlay.addEventListener('mousemove', handleMouseMove);
    textOverlay.addEventListener('mouseup', handleMouseUp);
    textOverlay.addEventListener('mouseleave', handleMouseUp);

    // 添加滚轮事件监听器
    textOverlay.addEventListener('wheel', handleWheel, { passive: false });

    // 防止文本选择
    textOverlay.addEventListener('selectstart', (e) => e.preventDefault());
    textOverlay.addEventListener('dragstart', (e) => e.preventDefault());
  } catch (error) {
    console.error('初始化拖拽和缩放失败:', error);
  }
}

// 处理触摸开始
function handleTouchStart(e) {
  try {
    if (e.touches.length === 2) {
      // 双指缩放
      lastDistance = getTouchDistance(e.touches);
      baseScale = scale;
    } else if (e.touches.length === 1) {
      // 单指拖动
      isDragging = true;
      initialX = e.touches[0].clientX - textOverlay.offsetLeft;
      initialY = e.touches[0].clientY - textOverlay.offsetTop;
    }
  } catch (error) {
    console.error('处理触摸开始失败:', error);
  }
}

// 处理触摸移动
function handleTouchMove(e) {
  try {
    e.preventDefault();
    
    if (e.touches.length === 2) {
      // 双指缩放
      const distance = getTouchDistance(e.touches);
      scale = baseScale * (distance / lastDistance);
      scale = Math.min(Math.max(0.5, scale), 3); // 限制缩放范围
      updateTextOverlayTransform(scale);
    } else if (e.touches.length === 1 && isDragging) {
      // 单指拖动
      const touchX = e.touches[0].clientX;
      const touchY = e.touches[0].clientY;
      
      currentX = touchX - initialX;
      currentY = touchY - initialY;
      
      updateTextOverlayPosition(currentX, currentY);
    }
  } catch (error) {
    console.error('处理触摸移动失败:', error);
  }
}

// 处理触摸结束
function handleTouchEnd() {
  isDragging = false;
}

// 处理鼠标按下
function handleMouseDown(e) {
  try {
    isDragging = true;
    initialX = e.clientX - textOverlay.offsetLeft;
    initialY = e.clientY - textOverlay.offsetTop;
  } catch (error) {
    console.error('处理鼠标按下失败:', error);
  }
}

// 处理鼠标移动
function handleMouseMove(e) {
  try {
    if (isDragging) {
      e.preventDefault();
      currentX = e.clientX - initialX;
      currentY = e.clientY - initialY;
      updateTextOverlayPosition(currentX, currentY);
    }
  } catch (error) {
    console.error('处理鼠标移动失败:', error);
  }
}

// 处理鼠标松开
function handleMouseUp() {
  isDragging = false;
}

// 处理滚轮事件
function handleWheel(e) {
  try {
    e.preventDefault();
    const delta = e.deltaY > 0 ? 0.9 : 1.1;
    scale *= delta;
    scale = Math.min(Math.max(0.5, scale), 3);
    updateTextOverlayTransform(scale);
  } catch (error) {
    console.error('处理滚轮事件失败:', error);
  }
}

// 获取触摸点之间的距离
function getTouchDistance(touches) {
  return Math.hypot(
    touches[1].clientX - touches[0].clientX,
    touches[1].clientY - touches[0].clientY
  );
}

// 更新文本位置和大小
function updateTextOverlayPosition(x, y) {
  try {
    // 确保文本框不会完全移出视图
    const maxX = window.innerWidth - textOverlay.offsetWidth / 2;
    const maxY = window.innerHeight - textOverlay.offsetHeight / 2;
    const minX = textOverlay.offsetWidth / 2;
    const minY = textOverlay.offsetHeight / 2;
    
    x = Math.min(Math.max(x, minX), maxX);
    y = Math.min(Math.max(y, minY), maxY);
    
    textOverlay.style.left = `${x}px`;
    textOverlay.style.top = `${y}px`;
  } catch (error) {
    console.error('更新文本位置失败:', error);
  }
}

function updateTextOverlayTransform(s) {
  try {
    textOverlay.style.transform = `translate(-50%, -50%) scale(${s})`;
  } catch (error) {
    console.error('更新文本变换失败:', error);
  }
}

// 开始拍摄
function startCapture() {
  try {
    console.log('开始拍摄函数被调用');
    console.log('延时模式:', delayMode);
    console.log('视频模式:', isVideoMode);

    // Check if delay mode is active
    if (delayMode > 0) {
      console.log('启动延时拍摄倒计时');
      startCountdown();
      return;
    }

    if (isVideoMode) {
      console.log('开始录像');
      startRecording();
    } else {
      console.log('开始拍照');
      capturePhoto();
    }
  } catch (error) {
    console.error('开始拍摄失败:', error);
    alert('拍摄失败，请重试');
  }
}

// 拍照
function capturePhoto() {
  try {
    // 创建临时画布
    const tempCanvas = document.createElement('canvas');
    const tempCtx = tempCanvas.getContext('2d');
    
    // 设置画布尺寸
    tempCanvas.width = video.videoWidth;
    tempCanvas.height = video.videoHeight;
    
    // 绘制视频帧
    tempCtx.drawImage(video, 0, 0);
    
    // 如果有文本覆盖层，绘制文本
    if (textOverlay && textOverlay.classList.contains('active')) {
      const textRect = textOverlay.getBoundingClientRect();
      const videoRect = video.getBoundingClientRect();
      
      const scaleX = tempCanvas.width / videoRect.width;
      const scaleY = tempCanvas.height / videoRect.height;
      
      tempCtx.save();
      tempCtx.scale(scaleX, scaleY);
      tempCtx.translate(
        textRect.left - videoRect.left,
        textRect.top - videoRect.top
      );
      
      // 获取文本样式
      const style = window.getComputedStyle(textOverlay);
      tempCtx.font = style.font;
      tempCtx.fillStyle = style.color;
      tempCtx.textShadow = style.textShadow;
      tempCtx.textAlign = 'center';
      tempCtx.textBaseline = 'middle';
      
      // 绘制文本
      const textContent = textOverlay.querySelector('.text-content').textContent;
      tempCtx.fillText(textContent, textRect.width / 2, textRect.height / 2);
      tempCtx.restore();
    }
    
    // 创建下载链接
    const link = document.createElement('a');
    link.download = `photo_${new Date().toISOString().slice(0,19).replace(/:/g, '-')}.png`;
    link.href = tempCanvas.toDataURL('image/png');
    link.click();
  } catch (error) {
    console.error('拍照失败:', error);
    alert('拍照失败，请重试');
  }
}

// 开始录制
function startRecording() {
  try {
    if (!cameraStream || !audioStream) {
      throw new Error('未找到摄像头或麦克风流，请刷新页面重试');
    }

    // Combine existing video and audio streams
    const combinedTracks = [
      ...cameraStream.getTracks(),
      ...audioStream.getTracks()
    ];
    const combinedStream = new MediaStream(combinedTracks);

    // Start reference video if available
    if (mediaElement && isVideo) {
      mediaElement.play().catch(error => {
        console.error('无法播放参考视频:', error);
      });
    }

    // 更新mediaRecorder事件监听
  isAutoScrolling = true;
  const selectedSpeed = document.getElementById('text-scroll-speed').value;
  const baseSpeed = scrollSpeedPresets[selectedSpeed];
  scrollStartTime = Date.now();
  startAutoScroll();


    // Set up MediaRecorder
    const mimeTypes = [
      'video/webm;codecs=vp8,opus',
      'video/webm;codecs=vp9',
      'video/webm',
      'video/mp4'
    ];

    const supportedMimeType = mimeTypes.find(type => MediaRecorder.isTypeSupported(type));
    if (!supportedMimeType) {
      throw new Error('未找到支持的视频编码格式');
    }

    mediaRecorder = new MediaRecorder(combinedStream, {
      mimeType: supportedMimeType
    });

    recordedChunks = [];

    mediaRecorder.ondataavailable = (event) => {
      if (event.data && event.data.size > 0) {
        recordedChunks.push(event.data);
      }
    };

    mediaRecorder.onstop = () => {
      try {
        if (recordedChunks.length === 0) {
          throw new Error('未录制到任何数据');
        }
        const blob = new Blob(recordedChunks, { type: supportedMimeType });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `video_${new Date().toISOString().slice(0,19).replace(/:/g, '-')}.webm`;
        link.click();
        URL.revokeObjectURL(url);
        recordedChunks = [];
      } catch (error) {
        console.error('保存录制视频失败:', error);
        alert('保存录制视频失败，请重试');
      }
    };

    mediaRecorder.start(1000);
    isRecording = true;
    updateRecordingState(true);

  } catch (error) {
    console.error('开始录制失败:', error);
    alert('开始录制失败: ' + error.message);
    resetRecordingState();
  }
}


mediaRecorder.addEventListener('pause', () => {
  isPaused = true;
  pauseStartTime = Date.now();
  clearInterval(scrollInterval);
});

mediaRecorder.addEventListener('resume', () => {
  isPaused = false;
  const pausedDuration = Date.now() - pauseStartTime;
  scrollStartTime += pausedDuration;
  startAutoScroll(baseSpeed * autoScrollSpeed);
});
// 停止录制
function stopRecording() {
  try {
    if (mediaRecorder && isRecording) {
      mediaRecorder.stop();
      stopAutoScroll();
      // Ensure all audio tracks are stopped
      if (mediaRecorder.stream) {
        mediaRecorder.stream.getAudioTracks().forEach(track => {
          track.stop();
        });
      }
      
      mediaRecorder = null;
      isRecording = false;
      updateRecordingState(false);

      // Pause reference video
      if (mediaElement && isVideo) {
        mediaElement.pause();
      }

      if (recordingIndicator) {
        recordingIndicator.style.display = 'none';
        recordingIndicator.classList.remove('recording');
      }
    }
  } catch (error) {
    console.error('停止录制失败:', error);
    alert('停止录制失败，请重试');
    resetRecordingState();
  }
}

// 更新录制状态
function updateRecordingState(recording) {
  try {
    // Update capture button state
    if (captureBtn) {
      captureBtn.classList.toggle('recording', recording);
      captureBtn.title = recording ? '停止录制' : (isVideoMode ? '开始录制' : '拍照');
    }

    // Update recording indicator
    if (recordingIndicator) {
      recordingIndicator.style.display = recording ? 'block' : 'none';
      recordingIndicator.classList.toggle('recording', recording);
    }

    // Disable other control buttons
    if (photoModeBtn) photoModeBtn.disabled = recording;
    if (videoModeBtn) videoModeBtn.disabled = recording;
    if (delayBtn) delayBtn.disabled = recording;
    if (beautyFilterBtn) beautyFilterBtn.disabled = recording;
    if (normalFilterBtn) normalFilterBtn.disabled = recording;
    if (filterButtons) {
      filterButtons.forEach(btn => btn.disabled = recording);
    }

  } catch (error) {
    console.error('更新录制状态失败:', error);
    resetRecordingState();
  }
}

// 重置录制状态
function resetRecordingState() {
  try {
    isRecording = false;
    
    // Reset capture button
    if (captureBtn) {
      captureBtn.classList.remove('recording');
      captureBtn.disabled = false;
      captureBtn.title = isVideoMode ? '开始录制' : '拍照';
    }

    // Reset recording indicator
    if (recordingIndicator) {
      recordingIndicator.style.display = 'none';
      recordingIndicator.classList.remove('recording');
    }

    // Re-enable all control buttons
    if (photoModeBtn) photoModeBtn.disabled = false;
    if (videoModeBtn) videoModeBtn.disabled = false;
    if (delayBtn) delayBtn.disabled = false;
    if (beautyFilterBtn) beautyFilterBtn.disabled = false;
    if (normalFilterBtn) normalFilterBtn.disabled = false;
    if (filterButtons) {
      filterButtons.forEach(btn => btn.disabled = false);
    }

    // Clean up recorder but keep the stream active
    if (mediaRecorder) {
      if (mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
      }
      mediaRecorder = null;
    }
    recordedChunks = [];

  } catch (error) {
    console.error('重置录制状态失败:', error);
  }
}

// 初始化文本滚动控制
function initTextScrollControl() {
  try {
    const textOverlay = document.querySelector('#text-overlay');
    const playPauseBtn = textOverlay.querySelector('.play-pause-btn');
    const textContent = textOverlay.querySelector('.text-content');
    const closeBtn = textOverlay.querySelector('.close-btn');
    const scrollSpeedSelect = document.getElementById('text-scroll-speed');
    
    let scrollInterval = null;
    let isPaused = true;
    let currentSpeed = 40; // Default speed (pixels per second)

    function startTextScroll() {
      if (scrollInterval) clearInterval(scrollInterval);
      
      scrollInterval = setInterval(() => {
        if (!textContent) return;
        
        const maxScroll = textContent.scrollHeight - textContent.clientHeight;
        const newScrollTop = textContent.scrollTop + (currentSpeed / 60);

        if (newScrollTop >= maxScroll) {
          textContent.scrollTop = maxScroll;
          stopTextScroll();
          isPaused = true;
          updatePlayPauseButton(true);
        } else {
          textContent.scrollTop = newScrollTop;
        }
      }, 16); // ~60fps for smooth scrolling
    }

    function stopTextScroll() {
      if (scrollInterval) {
        clearInterval(scrollInterval);
        scrollInterval = null;
      }
    }

    function updatePlayPauseButton(isPlaying) {
      const playIcon = playPauseBtn.querySelector('.play-icon');
      const pauseIcon = playPauseBtn.querySelector('.pause-icon');
      
      if (playIcon && pauseIcon) {
        playIcon.style.display = isPlaying ? 'none' : 'block';
        pauseIcon.style.display = isPlaying ? 'block' : 'none';
      }
    }

    // Play/Pause button handler
    playPauseBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      isPaused = !isPaused;
      updatePlayPauseButton(!isPaused);
      
      if (isPaused) {
        stopTextScroll();
      } else {
        startTextScroll();
      }
    });

    // Speed control handler
    if (scrollSpeedSelect) {
      scrollSpeedSelect.addEventListener('change', () => {
        const value = scrollSpeedSelect.value;
        if (value === 'custom') {
          const customDuration = document.getElementById('custom-scroll-duration');
          if (customDuration) {
            currentSpeed = 40 * (60 / parseInt(customDuration.value));
          }
        } else {
          switch (value) {
            case 'very-slow': currentSpeed = 20; break;
            case 'slow': currentSpeed = 30; break;
            case 'normal': currentSpeed = 40; break;
            case 'fast': currentSpeed = 50; break;
            case 'very-fast': currentSpeed = 60; break;
          }
        }

        if (!isPaused) {
          stopTextScroll();
          startTextScroll();
        }
      });
    }

    // Close button handler
    closeBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      stopTextScroll();
      textOverlay.style.display = 'none';
      textOverlay.classList.remove('active');
    });

    // Reset scroll position when showing new text
    textContent.scrollTop = 0;
    updatePlayPauseButton(false);

  } catch (error) {
    console.error('初始化文本滚动控制失败:', error);
  }
}
function onPauseClick() {
  const pauseIcon = document.querySelector('.pause-icon');
  const playIcon = document.querySelector('.play-icon');
  pauseIcon.style.display = paused.current? 'flex' : 'none';
  playIcon.style.display = paused.current ? 'none' : 'flex';
  paused.current =!paused.current;

}

// 停止自动滚动
function stopAutoScroll() {
  try {
    if (scrollInterval) {
      clearInterval(scrollInterval);
      scrollInterval = null;
    }
    isAutoScrolling = false;
    paused.current = false;
  } catch (error) {
    console.error('停止自动滚动失败:', error);
  }
}
// 开始自动滚动
function startAutoScroll() {
  try {
    if (!textOverlay || !textOverlay.classList.contains('active')) {
      throw new Error('文本覆盖层未激活');
    }

    const textContainer = textOverlay.querySelector('.text-content');
    if (!textContainer) {
      throw new Error('文本容器未找到');
    }

    stopAutoScroll();
    isAutoScrolling = true;
    scrollStartTime = Date.now();
    scrollInterval = setInterval(() => {
      if (!paused.current) {
        console.log("start")
        const elapsed = Date.now() - scrollStartTime;
        const scrollPosition = (elapsed / (autoScrollSpeed * 1000)) * textContainer.scrollHeight;
        textContainer.style.transform = `translateY(-${scrollPosition}px)`
        console.log("滚动1次",autoScrollSpeed,scrollPosition)

        if (scrollPosition >= textContainer.scrollHeight) {
          stopAutoScroll();
        }
      }
    }, 16); // 约60fps
  } catch (error) {
    console.error('开始自动滚动失败:', error);
    alert('无法开始自动滚动，请重试');
    stopAutoScroll();
  }
}


// 初始化延时拍摄按钮
function initDelayButton() {
  try {
    const delayBtn = document.getElementById('delay-btn');
    if (!delayBtn) {
      throw new Error('延时按钮未找到');
    }

      delayBtn.addEventListener('click', () => {
        try {
        // If recording or countdown is in progress, don't allow changes
        if (countdownTimer || isRecording) {
          console.log('录制或倒计时进行中，无法更改延时模式');
          return;
        }
        
        // Update delay mode and button appearance
          switch (delayMode) {
            case 0:
              delayMode = 3;
              delayBtn.classList.remove('delay-0');
              delayBtn.classList.add('delay-3');
              delayBtn.title = '3秒延时';
            console.log('设置3秒延时');
              break;
            case 3:
              delayMode = 6;
              delayBtn.classList.remove('delay-3');
              delayBtn.classList.add('delay-6');
              delayBtn.title = '6秒延时';
            console.log('设置6秒延时');
              break;
            case 6:
              delayMode = 0;
              delayBtn.classList.remove('delay-6');
              delayBtn.classList.add('delay-0');
              delayBtn.title = '无延时';
            console.log('取消延时');
              break;
          }
        } catch (error) {
          console.error('切换延时模式失败:', error);
          alert('无法切换延时模式，请重试');
        // Reset delay state
          delayMode = 0;
          delayBtn.classList.remove('delay-3', 'delay-6');
          delayBtn.classList.add('delay-0');
          delayBtn.title = '无延时';
        }
      });
  } catch (error) {
    console.error('初始化延时按钮失败:', error);
    alert('初始化延时按钮失败，请刷新页面重试');
  }
}

// Add this new function to initialize reference controls
function initReferenceControls() {
  try {
    const referenceControls = document.querySelector('.reference-controls');
    
    if (!referenceControls || !videoProgress || !playPauseBtn) {
      throw new Error('Reference control elements not found');
    }

    // Progress bar update
    videoProgress.addEventListener('input', (e) => {
      if (mediaElement && isVideo) {
        const time = (mediaElement.duration * e.target.value) / 100;
        mediaElement.currentTime = time;
        updateTimeDisplay(time, mediaElement.duration);
      }
    });

    // Play/Pause button
    playPauseBtn.addEventListener('click', togglePlayPause);

    // Update progress bar as video plays
    if (mediaElement) {
      mediaElement.addEventListener('timeupdate', updateVideoProgress);
    }
  } catch (error) {
    console.error('初始化参考视频控制失败:', error);
  }
}

// Add these new functions for video control
function togglePlayPause() {
  try {
    if (!mediaElement || !isVideo) return;

    if (mediaElement.paused) {
      mediaElement.play();
    } else {
      mediaElement.pause();
    }
  } catch (error) {
    console.error('切换播放/暂停失败:', error);
  }
}

function updatePlayPauseButton(isPlaying) {
  try {
    const playIcon = playPauseBtn.querySelector('.play-icon');
    const pauseIcon = playPauseBtn.querySelector('.pause-icon');
    
    if (playIcon && pauseIcon) {
      playIcon.style.display = isPlaying ? 'none' : 'block';
      pauseIcon.style.display = isPlaying ? 'block' : 'none';
    }

    // Update recording button state if recording is in progress
    if (isRecording) {
      if (captureBtn) {
        captureBtn.classList.toggle('recording', isPlaying);
      }
    }
  } catch (error) {
    console.error('更新播放/暂停按钮失败:', error);
  }
}

function formatTime(seconds) {
  try {
    if (!isFinite(seconds) || isNaN(seconds)) {
      return '0:00';
    }
    const minutes = Math.floor(seconds / 60);
    seconds = Math.floor(seconds % 60);
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  } catch (error) {
    console.error('格式化时间失败:', error);
    return '0:00';
  }
}

// Add this function to handle video synchronization
function synchronizeVideoPlayback() {
  try {
    if (mediaElement && isVideo) {
      mediaElement.currentTime = 0;
      return mediaElement.play();
    }
    return Promise.resolve();
  } catch (error) {
    console.error('同步视频播放失败:', error);
    return Promise.reject(error);
  }
}
// 调整滚动文字大小
function changeFontSize(changed) {
  const textContent = document.querySelector('.text-content');
  const textSize= document.querySelector("#text-size")
  textContent.style.fontSize = `${parseInt(getComputedStyle(textContent).getPropertyValue('font-size')) + changed}px`;
  textSize.setAttribute("value",parseInt(textContent.style.fontSize))
}
function hideTextControl () {
  const panel = document.getElementById('text-control-panel')
  panel.style.display = 'none'
   const showControls = document.getElementById('show-controls')
  showControls.style.display = 'block'
}
function showControls () {
  const panel = document.getElementById('text-control-panel')
  panel.style.display = 'block'
  const showControls = document.getElementById('show-controls')
  showControls.style.display = 'none'
}
function resetTextPosition () {
       console.log('重置文本位置按钮被触摸', resetTextPositionBtn);
   const textContent = document.querySelector('.text-content');
      textContent.style.transform = 'translateY(0px)';
      stopAutoScroll()
}
// Add touch event handling for better mobile experience
function initTouchHandling() {
  try {
    const controls = document.querySelectorAll('.control-btn, .capture-button, .mode-btn');

    controls.forEach(control => {
      // Add active state for touch feedback
      control.addEventListener('touchstart', function(e) {
        this.classList.add('active');
      });

      control.addEventListener('touchend', function(e) {
        this.classList.remove('active');
      });

      // Prevent default touch behavior
      control.addEventListener('touchmove', function(e) {
        e.preventDefault();
      });
    });

    // Improve progress bar touch handling
    const progressBar = document.querySelector('.progress-bar');
    if (progressBar) {
      let touchActive = false;

      progressBar.addEventListener('touchstart', function(e) {
        touchActive = true;
        this.classList.add('active');
      });

      progressBar.addEventListener('touchmove', function(e) {
        if (touchActive) {
          const touch = e.touches[0];
          const rect = this.getBoundingClientRect();
          const position = (touch.clientX - rect.left) / rect.width;
          const value = Math.max(0, Math.min(100, position * 100));
          this.value = value;
          handleProgressBarInput({ target: this });
        }
      });

      progressBar.addEventListener('touchend', function(e) {
        if (touchActive) {
          touchActive = false;
          this.classList.remove('active');
          handleProgressBarChange({ target: this });
        }
      });
    }
  } catch (error) {
    console.error('初始化触摸事件处理失败:', error);
  }
}

// Add a proper shutdown function for when the app closes
function shutdownApp() {
  try {
    // Stop all tracks
    if (cameraStream) {
      cameraStream.getTracks().forEach(track => track.stop());
    }
    if (audioStream) {
      audioStream.getTracks().forEach(track => track.stop());
    }
    
    // Clear streams
    cameraStream = null;
    audioStream = null;
    
    // Clean up other resources
    cleanup();
  } catch (error) {
    console.error('关闭应用程序失败:', error);
  }
}

// Handle app shutdown
window.addEventListener('beforeunload', () => {
  shutdownApp();
});